package com.stray.crawl.expr.psr;

import com.stray.crawl.expr.EventData;
import com.stray.crawl.expr.Express;

public class SubstrParser extends Express {

	@Override
	protected Object doParse(EventData event) {
		Object obj = event.getObject();
		String args = event.getArguments();
		String[] argsArray = event.toStringArrayArgument();

		String str = (String) obj;
		int fmIdx = -1, toIdx = -1;

		if (argsArray.length > 1) {
			String fm = argsArray[0];
			String to = argsArray[1];

			fmIdx = str.indexOf(fm);
			if (fmIdx >= 0) {
				fmIdx += fm.length();
				toIdx = str.indexOf(to, fmIdx);
			}
		} else {
			char idr = args.charAt(0);
			String search = args.substring(1);

			if (idr == '>') {
				// as substr after
				fmIdx = str.indexOf(search) + search.length();
			} else if (idr == '<') {
				// as substr before
				toIdx = str.lastIndexOf(search);
			}
		}

		fmIdx = fmIdx > 0 ? fmIdx : 0;
		toIdx = toIdx > fmIdx && toIdx <= str.length() ? toIdx : str.length();

		return str.substring(fmIdx, toIdx);
	}

}
